<template>
  <el-card class="card">
    <div slot="header">
      <span>投诉</span>
    </div>
    <!-- <p class="tips">
      当前业务暂未开通，请耐心等待!
    </p> -->
    <div>
      <div class="h-warp">
        <div class="title"><i class="el-icon-s-promotion title-icon" />投诉</div>
        <el-button type="primary" size="mini" icon="el-icon-plus" @click="add" />
      </div>

      <div v-for="(item,idx) in compalintRecord" :key="idx" class="c-warp">
        <el-form :inline="true" :model="item">
          <el-form-item label="投诉类型:">
            <el-select v-model="item.complaintType" placeholder="请选择投诉类型" @change="getComplaintContent(item,idx)">
              <el-option
                v-for="ele in complaintTypeList"
                :key="ele.key"
                :label="ele.desc"
                :value="ele.key"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="投诉内容:">
            <el-checkbox-group v-model="item.complaintContent">
              <el-checkbox v-for="(e,index) in item.complaintContentList" :key="index" :label="e" />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="关联订单:">
            <el-select v-model="item.order" placeholder="请选择关联订单" @change="orderChange(item,idx)">
              <el-option
                v-for="(ele,index) in orderList"
                :key="index"
                :label="ele.orderCode"
                :value="ele.orderCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="item.complaintType !=='GAS'&& item.complaintType !=='STATION'" label="被投诉人:">
            <el-select v-model="item.complainUser" filterable placeholder="请选择被投诉人">
              <el-option
                v-for="(ele,index) in item.complainUserList"
                :key="index"
                :label="ele.userName"
                :value="ele.userId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="处理机构:">
            <el-select v-model="item.org" :disabled="item.complaintType==='PARTS'||item.complaintType==='DELIVERY'" placeholder="请选择处理机构" @change="orgChange(item,idx)">
              <el-option
                v-for="(ele,index) in item.orgList"
                :key="index"
                :label="ele.orgName"
                :value="ele.orgId"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="(item.complaintType==='PARTS'||item.complaintType==='DELIVERY'|| ((item.complaintType==='OTHERS')&&!item.isCallcenter)) && (!item.isDisabled)" label="处理人:">
            <el-select v-model="item.user" placeholder="请选择处理人" filterable>
              <el-option
                v-for="(ele,index) in item.userList"
                :key="index"
                :label="ele.userName"
                :value="ele.userId"
              />
            </el-select>
          </el-form-item>
          <el-input v-model="item.complainText" class="textarea" maxlength="200" show-word-limit type="textarea" :rows="3" placeholder="请输入内容" />
          <svg-icon v-if="compalintRecord.length > 1" icon-class="remove" class="remove-icon" @click="removeRecord(item,idx)" />
        </el-form>
      </div>

      <el-button
        :loading="isOnSubmit"
        type="primary"
        class="submitBtn"
        @click="submit"
      >提交投诉登记</el-button>
    </div>
    <reminderDialog ref="reminderDialog" :client-selected="clientSelected" />
    <chargebackDialog ref="chargebackDialog" type="complain" />
    <exchangeDialog ref="exchangeDialog" :client-selected="clientSelected" />
  </el-card>
</template>

<script>
  import reminderDialog from './reminderDialog.vue'
  import chargebackDialog from './chargebackDialog.vue'
  import exchangeDialog from './exchangeDialog.vue'
  // import { parseTime } from '@/utils'
  // import dayjs from 'dayjs'
  import { complainOrgList, complainUserList, csDeliverUserList, findRelationOrderList, getComplainAttrs, getComplainType, saveComplains } from '@/api'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  export default {
    name: 'call-complaint',
    components: { reminderDialog, chargebackDialog, exchangeDialog },
    props: {
      temp: {
        type: Object,
        default: () => { return {} }
      },
      userData: {
        type: Object,
        default: () => { return {} }
      },
      currentPhoneData: {
        type: Object,
        default: () => { return {} }
      },
      clientSelected: {
        type: Object,
        default: () => {
          return {}
        }
      },
      shippingInfoSelected: {
        type: Object,
        default: () => {
          return {}
        }
      }
    },
    data() {
      return {
        checkboxList: ['送气速度慢', '服务态度差', '乱收费', '系统违规操作', '抢修抢险不及时', '其他'],
        checkList: [],
        tableData: [],
        isOnSubmit: false,
        complaintTypeList: [],
        orderList: [],
        compalintRecord: [{
          id: 0,
          complainContent: '',
          complaintType: '',
          complaintContent: [],
          order: '',
          org: '',
          user: '',
          complainUser: '',
          orgList: [],
          userList: [],
          complainUserList: [],
          complaintContentList: [],
          isCallcenter: false,
          complainText: '',
          isDisabled: false
        }]
      }
    },

    created() {
    },
    mounted() {
    },
    methods: {
      async getInitData() {
        const [res1] = await Promise.all([
          mergeAsyncFunc(getComplainType, {})
        ])
        if (res1 && res1.data) {
          this.complaintTypeList = res1.data
        }
      },
      // 投诉内容
      async getComplaintContent(val, i) {
        this.clearData(i)
        const param = {
          key: val.complaintType
        }
        const res = await getComplainAttrs(param, i)
        if (res && res.data) {
          this.compalintRecord[i].complaintContentList = res.data
        }
        await this.getRelationOrderList(val)
        await this.getComplainOrgList(i)
        if (val.complaintType === 'PARTS' || val.complaintType === 'DELIVERY') {
          let org = this.orderList[0]
          if (val.order) {
            org = this.orderList.find(item => item.orderCode === val.order)
          }
          this.compalintRecord[i].org = org && org.orgId
          if (this.compalintRecord[i].org) {
            this.getIsDisabled(this.compalintRecord[i], i)
          }
          this.getComplaintHandleUser(this.compalintRecord[i], i)
        } else if (val.complaintType === 'OTHERS') {
          this.compalintRecord[i].org = ''
          this.compalintRecord[i].isCallcenter = false
        } else {
          const org = this.compalintRecord[i].orgList.find(item => item.orgType === 15)
          this.compalintRecord[i].org = org && org.orgId
          this.compalintRecord[i].isCallcenter = true
        }
        this.getComplaintUser(this.compalintRecord[i], i)
      },
      async getRelationOrderList(val) {
        const params = {
          corpSN: this.clientSelected.corpSN,
          complainType: this.complaintTypeList.find(e => e.key === val.complaintType).value,
          csmId: this.clientSelected.csmId
        }
        const res = await findRelationOrderList(params)
        if (res && res.data) {
          this.orderList = res.data
        }
      },
      clearData(i) {
        this.compalintRecord[i].complaintContent = []
        this.compalintRecord[i].order = ''
        this.compalintRecord[i].org = ''
        this.compalintRecord[i].user = ''
        this.compalintRecord[i].complainUser = ''
      },
      // 被投诉人
      async getComplaintUser(val, i) {
        if (!val.org) return
        this.compalintRecord[i].complainUserList = []
        if (val.complaintType === 'CALLCENTER') {
          const param = {
            corpSN: 0,
            orgType: 15,
            utype: 8
          }
          const res = await complainUserList(param)
          if (res && res.data) {
            this.compalintRecord[i].complainUserList = res.data
          }
        } else {
          const param = {
            deliveryOrgId: val.org,
            containWebUserflag: 1
          }
          const res = await csDeliverUserList(param)
          if (res && res.data) {
            this.compalintRecord[i].complainUserList = res.data
          }
        }
      },
      orderChange(val, i) {
        this.compalintRecord[i].complainUser = ''
        this.compalintRecord[i].user = ''
        if (val.complaintType === 'PARTS' || val.complaintType === 'DELIVERY') {
          let org = this.orderList[0]
          if (val.order) {
            const order = this.orderList.find(item => item.orderCode === val.order)
            org = this.compalintRecord[i].orgList.find(item => item.orgId === order.orgId)
          }
          this.compalintRecord[i].org = org && org.orgId
          if (this.compalintRecord[i].org) {
            this.getIsDisabled(this.compalintRecord[i], i)
          }
          this.getComplaintHandleUser(this.compalintRecord[i], i)
        }
        this.getComplaintUser(this.compalintRecord[i], i)
      },
      orgChange(val, i) {
        this.compalintRecord[i].complainUser = ''
        this.compalintRecord[i].user = ''
        if (val.complaintType === 'PARTS' || val.complaintType === 'DELIVERY' || val.complaintType === 'OTHERS') {
          this.getComplaintHandleUser(this.compalintRecord[i], i)
        }
        const org = this.compalintRecord[i].orgList.find(item => item.orgId === val.org)
        if (org) {
          if (org.orgType === 15) {
            this.compalintRecord[i].isCallcenter = true
          } else {
            this.compalintRecord[i].isCallcenter = false
          }
        } else {
          this.compalintRecord[i].isCallcenter = false
        }

        if (this.compalintRecord[i].org) {
          this.getIsDisabled(this.compalintRecord[i], i)
        }
        this.getComplaintUser(this.compalintRecord[i], i)
      },
      // 处理人
      async getComplaintHandleUser(val, i) {
        this.compalintRecord[i].userList = []
        if (!val.org) return
        // const param = {
        //   corpSN: this.clientSelected.corpSN,
        //   orgId: val.org,
        //   complainType: this.complaintTypeList.find(e => e.key === val.complaintType).value
        // }
        // const res = await complainUserList(param)
        const param = {
          deliveryOrgId: val.org,
          containWebUserflag: 1
        }
        const res = await csDeliverUserList(param)
        if (res && res.data) {
          this.compalintRecord[i].userList = res.data
        }
      },
      // 查询处理机构
      async getComplainOrgList(i) {
        this.compalintRecord[i].orgList = []
        const param = {
          corpSN: this.compalintRecord[i].complaintType === 'GAS' ||
            this.compalintRecord[i].complaintType === 'STATION' ||
            this.compalintRecord[i].complaintType === 'CALLCENTER'
            ? 0 : this.clientSelected.corpSN
        }
        if (param.corpSN === 0) {
          param.orgType = 15
        }
        const res = await complainOrgList(param)
        if (res && res.data) {
          this.compalintRecord[i].orgList = res.data
        }
      },
      getIsDisabled(val, i) {
        const org = this.compalintRecord[i].orgList.find(item => item.orgId === val.org)
        if (org && ((org.sp1 >> 16 & 0x01) === 0)) {
          this.compalintRecord[i].isDisabled = false
        } else {
          this.compalintRecord[i].isDisabled = true
        }
      },
      // 催单
      async handleReminder(row) {
        await this.$refs.reminderDialog.open(row)
      },
      // 退单
      async handleChargeback(row) {
        await this.$refs.chargebackDialog.open(row)
      },
      // 流转
      async handleExchange(row) {
        await this.$refs.exchangeDialog.open(row, 'complaint')
      },

      submit() {
        if (!(this.clientSelected && this.clientSelected.csmCode)) {
          this.$message.error('请选择客户信息后操作')
          return
        }
        const isComplaintType = this.compalintRecord.every(item => item.complaintType)
        if (!isComplaintType) {
          this.$message.error('投诉类型为必选项')
          return
        }
        const isComplaintContent = this.compalintRecord.every(item => ((item.complaintContent && item.complaintContent.length > 0) || item.complainText))
        if (!isComplaintContent) {
          this.$message.error('请选择或填写投诉内容')
          return
        }

        const f = this.compalintRecord.find(item => (item.complaintType === 'PARTS' || item.complaintType === 'DELIVERY' || item.complaintType === 'GAS') && !item.order)
        if (f) {
          this.$message.error('关联订单号为必填')
          return
        }
        const o = this.compalintRecord.every(item => item.org)
        if (!o) {
          this.$message.error('处理机构为必选项')
          return
        }
        this.compalintRecord = this.compalintRecord.map((item) => ({
          callPhone: this.temp.phone,
          complainContent: item.complaintContent.join(','),
          complainType: this.complaintTypeList.find(e => e.key === item.complaintType).value,
          complainUserId: item.complainUser,
          complainUserName: item.complainUser ? item.complainUserList.find(e => e.userId === item.complainUser).userName : '',
          corpSN: this.clientSelected.corpSN,
          csmAddressId: this.shippingInfoSelected.csmAddressId,
          csmAddress: this.shippingInfoSelected.provinceName + this.shippingInfoSelected.cityName + this.shippingInfoSelected.countryName + this.shippingInfoSelected.csmAddress,
          csmId: this.clientSelected.csmId,
          fromPlat: 7,
          orgId: item.org,
          orgName: item.org ? item.orgList.find(e => e.orgId === item.org).orgName : '',
          orgSNNo: item.org ? item.orgList.find(e => e.orgId === item.org).orgSNNo : '',
          orderCode: item.order,
          userId: item.user,
          userName: item.user ? item.userList.find(e => e.userId === item.user).userName : '',
          remark: item.complainText
        }))

        this.isOnSubmit = true
        saveComplains(this.compalintRecord).then(res => {
          if (res.data) {
            this.$message.success('操作成功')
            this.isOnSubmit = false
            this.reset()
            this.$emit('onSubmit')
          }
        })
      },
      add() {
        this.compalintRecord.push({
          id: this.compalintRecord.length + 1,
          complainContent: '',
          complaintType: '',
          complaintContent: [],
          order: '',
          org: '',
          user: '',
          complainUser: '',
          orgList: [],
          userList: [],
          complainUserList: [],
          complaintContentList: [],
          isCallcenter: false,
          complainText: '',
          isDisabled: false

        })
      },
      removeRecord(val, i) {
        this.compalintRecord.splice(i, 1)
      },
      reset() {
        this.compalintRecord = [{
          id: 0,
          complainContent: '',
          complaintType: '',
          complaintContent: [],
          order: '',
          org: '',
          user: '',
          complainUser: '',
          orgList: [],
          userList: [],
          complainUserList: [],
          complaintContentList: [],
          isCallcenter: false,
          complainText: '',
          isDisabled: false
        }]
      }
    }
  }
</script>

<style lang="scss" scoped>
.card {
  border-radius: 8px;
  & /deep/ .el-card__header {
    padding-bottom: 10px;
    padding-left: 10px;
    font-size: 14px;
    font-weight: bold;
  }
  & /deep/ .el-card__body {
    // min-height: 100px;
    // padding: 10px;
    min-height: 156px;
    padding: 10px;
    .tips {
      font-size: 14px;
    }
    .title {
      margin-right: 10px;
      font-size: 16px;
      font-weight: 600;
      color: #ED912E;
      .title-icon {
        margin-right: 2px;
        font-size: 19px;
      }
    }

    .title-table {
      padding: 15px 0;
      font-size: 16px;
      font-weight: 600;
      color: #F56C6C;
    }
    .submitBtn {
      float: right;
      margin: 10px 0;
    }
    .btnText {
      font-size: 14px;
    }
  }
  .h-warp {
    display: flex;
    padding: 10px 0;
    /deep/ .el-button {
      height: 24px;
      padding: 0 15px;
    }
  }
  .c-warp {
    position: relative;
    padding: 8px 16px  8px 8px;
    margin-bottom: 10px;
    border: 1px solid #e3e3e3;
    .remove-icon {
      position: absolute;
      top: 8px;
      right: 8px;
      font-size: 32px;
      cursor: pointer;
    }
  }
}
</style>
